package com.abc.intellihome.controller;

import com.abc.intellihome.domain.User;
import com.abc.intellihome.service.UserService;
import com.abc.intellihome.util.ResultInfo;
import com.abc.intellihome.util.ResultType;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping ("/register")
    public ResultInfo register(User user){
        int count = userService.register(user);
        ResultInfo resultInfo;
        if (count!=1){
            resultInfo = ResultInfo.getFailInfo();
            return resultInfo;
        }
        resultInfo = ResultInfo.getSuccessInfo();
        return resultInfo;
    }

    @PostMapping("/login")
    public ResultInfo loginUser(User user){
        ResultInfo resultInfo= new ResultInfo();
        User u = userService.loginUser(user);
       if (u!=null && u.password.equals(user.password)){
           resultInfo.setResultType(ResultType.success);
           resultInfo.setResultData(user);
           return resultInfo;
       }
        resultInfo.setResultType(ResultType.fail);
        return resultInfo;
    }

    @PutMapping("/update")
    public ResultInfo changeUserPassword(@RequestBody User user){
        System.out.println(user);
        int result = userService.changePassword(user);
        ResultInfo resultInfo;
        if (result==1){
            resultInfo=ResultInfo.getSuccessInfo();
            return resultInfo;
        }
        resultInfo =ResultInfo.getFailInfo();
        return resultInfo;

    }

    @GetMapping("{username}/pic")
    public String listElf(@PathVariable String username, HttpServletResponse response , HttpServletRequest request) throws IOException {
        byte[] avatar = userService.getUserAvatar(username);
        response.setContentType("image/jpeg");
        ServletOutputStream oos = response.getOutputStream();
        oos.write(avatar);
        oos.flush();
        oos.close();

        return null;
    }



}
